require(nnet)

score <- function(actual, observed, classes, confidence) {
    result = NULL    

    col = 1
    colSize = length(classes)
    while(col <= colSize) {
        classValues = NULL
	compare = cbind(actual[,col],observed[,col])
	actualCol = actual[,col]
	#observedCol = observed[,col]
	classValues$TP = as.numeric(length(which(compare[which(compare[,1] == compare[,2],arr.ind=T),1] == 1)))
	classValues$TN = as.numeric(length(which(compare[which(compare[,1] == compare[,2],arr.ind=T),1] == 0)))
	classValues$FP = as.numeric(length(which(compare[,1] < compare[,2])))
	classValues$FN = as.numeric(length(which(compare[,1] > compare[,2])))

	#classValues$TPcon = mean(confidence[which(actualCol > 0 && observedCol > 0)])
	#classValues$TNcon = mean(confidence[which(actualCol < 1 && observedCol < 1)])
	#classValues$FPcon = mean(confidence[which(actualCol < 1 && observedCol > 0)])
	#classValues$FNcon = mean(confidence[which(actualCol > 0 && observedCol < 1)])
	result = rbind(result,classValues)

	col = col + 1
    }
    rownames(result) = classes
    return(result)
}

precisionRecallFmeasure <- function(scores) {
    result = NULL
    for (class in rownames(scores)) {
        score = NULL
	score$precision = as.numeric(scores[class,"TP"])/(as.numeric(scores[class,"TP"])+as.numeric(scores[class,"FP"]))
	score$recall = as.numeric(scores[class,"TP"])/(as.numeric(scores[class,"TP"])+as.numeric(scores[class,"FN"]))
	score$fmeasure = 2*(score$precision*score$recall)/(score$precision+score$recall)
	result = rbind(result,score)
    }
    score = NULL
    sums = colSums(scores)
    score$precision = sums["TP"]/(sums["TP"]+sums["FP"])
    score$recall = sum(as.array(scores[,"TP"]))/(sum(as.array(scores[,"TP"]))+sum(as.array(scores[,"FN"])))
    score$fmeasure = 2*(score$precision*score$recall)/(score$precision+score$recall)
    result = rbind(result,score)
    rownames(result) = c(rownames(scores),"global")
    return(result)
}

classify <- function(table) {
    result = NULL
    calls = NULL

    for (rowname in rownames(table)) {
    	line = table[rowname,]
    	call = vector(mode="numeric",length=length(line))
	column = which.max(line)
	call[column] = 1.0
	result$calls = rbind(result$calls,call)
	result$confidence = c(result$confidence,mean(line[-column]))
    }
    return(result)
}

bestSOM <- function(table) {
    result = NULL;
    for (column in colnames(table)) {
        result <- c(result,which.is.max(table[,column]));
    }
    return(result);
}
